package com.xy.p2p.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.xy.common.page.Pagination;
import com.xy.common.security.BadCredentialsException;
import com.xy.common.security.UsernameNotFoundException;
import com.xy.common.security.encoder.PwdEncoder;
import com.xy.common.web.RequestUtils;
import com.xy.core.service.impl.BaseServiceImpl;
import com.xy.core.util.BeanUtil;
import com.xy.p2p.action.admin.TuserAction;
import com.xy.p2p.dao.TuserDao;
import com.xy.p2p.model.Tuser;
import com.xy.p2p.service.TuserService;
public class TuserServiceImpl extends BaseServiceImpl<Tuser> implements
		TuserService {
	@Autowired
	private PwdEncoder pwdEncoder;
	@Autowired
	private TuserDao tuserDao;

	public TuserServiceImpl(TuserDao paramAppRoleDao) {
		super(paramAppRoleDao);
		this.tuserDao = paramAppRoleDao;
	}

	public Tuser login(HttpServletRequest request,String username, String password)
			throws UsernameNotFoundException, BadCredentialsException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", username);

		List<Tuser> l = getTuser(map);

		if (l.size() == 0||"-1".equals(l.get(0).getStatus())) {
			throw new UsernameNotFoundException("用户名或密码不正确");
		}
		Tuser user = l.get(0);
		String ip = RequestUtils.getIpAddr(request);
		if (!pwdEncoder.isPasswordValid(user.getPasswd(), password)) {
			updateLoginError(user, ip);
			throw new BadCredentialsException("用户名或密码不正确");
		}
	/*	if (!user.getActivation()) {
			throw new BadCredentialsException("account not activated");
		}*/
		updateLoginSuccess(user, ip);
		request.getSession().setAttribute(TuserAction.AUTH_KEY, user);
		return user;
	}

	public void updateLoginSuccess(Tuser user,String ip) {/*
		UnifiedUser user = findById(userId);
		Date now = new Timestamp(System.currentTimeMillis());

		user.setLoginCount(user.getLoginCount() + 1);
		user.setLastLoginIp(ip);
		user.setLastLoginTime(now);

		user.setErrorCount(0);
		user.setErrorTime(null);
		user.setErrorIp(null);
	*/}

	public void updateLoginError(Tuser user,String ip) {/*
		UnifiedUser user = findById(userId);
		Date now = new Timestamp(System.currentTimeMillis());
		ConfigLogin configLogin = configMng.getConfigLogin();
		int errorInterval = configLogin.getErrorInterval();
		Date errorTime = user.getErrorTime();

		user.setErrorIp(ip);
		if (errorTime == null
				|| errorTime.getTime() + errorInterval * 60 * 1000 < now
						.getTime()) {
			user.setErrorTime(now);
			user.setErrorCount(1);
		} else {
			user.setErrorCount(user.getErrorCount() + 1);
		}
	*/}

	@Override
	public boolean checkExist(String paraName, String paraValue) {
		return tuserDao.checkExist("Tuser", paraName, paraValue);
	}

	@Override
	public List<Tuser> getTuser(Map<String, Object> map) {
		return tuserDao.getTuser(map);
	}
	@Override
	public Pagination getTuserByPage(Map<String, Object> map, int pageNo,
			int pageSize) {
		// TODO Auto-generated method stub
		return tuserDao.getTuserByPage(map, pageNo, pageSize);
	}
	@Override
	public Tuser save(Tuser tuser) {
		tuser.setModtime(new Date());
		if(tuser.getUserid()==null){
			//新增
			//String ip = RequestUtils.getIpAddr(request);
			//tuser.setRegip(ip);
			tuser.setRegtime(new Date());
			tuser.setPasswd(pwdEncoder.encodePassword(tuser.getPasswd()));
            tuser.setStatus("0");
        	return super.save(tuser);
		}else{
			//更新
			Tuser tuser1=tuserDao.get(tuser.getUserid());
			try {
				if(tuser1.getPasswd().equals(tuser.getPasswd())||tuser1.getPasswd().equals(pwdEncoder.encodePassword(tuser.getPasswd())))
					tuser.setPasswd(null);
				else
					tuser.setPasswd(pwdEncoder.encodePassword(tuser.getPasswd()));
				BeanUtil.copyNotNullProperties(tuser1, tuser);
			} catch (Exception e) {
				e.printStackTrace();
			}  
			return super.save(tuser1);
		}
	}
}